﻿using System;
using Events.Data;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace Events.Web
{
	public partial class RegisterForEvent : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!this.IsPostBack)
			{
				var result = string.Empty;

				var email = Request.QueryString["Email"];
				var demandId = Request.QueryString["DemandId"];

				if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(demandId))
				{
					// In C# 4 we could use Guid.TryParse here; for the sake of Azure we have to do the old stuff :-(
					var demandGuid = Guid.Empty;
					try
					{
						demandGuid = new Guid(demandId);
					}
					catch (OverflowException)
					{
					}
					catch (FormatException)
					{
					}

					if (demandGuid == Guid.Empty)
					{
						result = "Invalid parameters. DemandId has to be a GUID.";
					}

					using (var context = HelfenHelfenEntities.Create())
					{
						try
						{
							var missionId = context.RegisterAndSaveChanges(demandGuid, email);
							if (RoleEnvironment.IsAvailable)
							{
								context.QueueRegistrationMail(missionId);
							}
							else
							{
								context.SendRegistrationConfirmation(missionId);
							}

							result = "You have been successfully registered for the mission. A confirmation email will be sent.";
						}
						catch (RegistrationException ex)
						{
							result = ex.Message;
						}
					}
				}
				else
				{
					result = "Missing parameters. Specify Email and DemandId.";
				}

				this.ResultFeedback.Text = result;
			}
		}
	}
}